//
//  YKChatDataCell.swift
//  MSinger
//
//  Created by Kevin on 2018/3/14.
//  Copyright © 2018年 InitialC. All rights reserved.
//

import UIKit

class MutaChatDataCell: UITableViewCell {
    
    var headerSegue: ValueClosure?
    
    var sendStateSegue: ValueClosure?

    var imgTapSegue: ValueSegue?

    //容器
    lazy var container: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.white
        return view
    }()
    //头像
    lazy var headerBtn: UIButton = {
        let button = UIButton()
        button.layer.cornerRadius = 4
        button.layer.masksToBounds = true
        button.addTarget(self, action: #selector(clickHeaderBtn), for: UIControlEvents.touchUpInside)
        return button
    }()
    //红点发送
    lazy var sendStateBtn: UIButton = {
        let button = UIButton()
        button.backgroundColor = UIColor.red
        button.layer.cornerRadius = 6
        button.layer.masksToBounds = true
        button.addTarget(self, action: #selector(clickSendBtn(sender:)), for: UIControlEvents.touchUpInside)
        button.isHidden = true
        return button
    }()
    //文本
    lazy var contentLalel: MenuLabel = {
        let label = MenuLabel()
        label.numberOfLines = 0
        label.isUserInteractionEnabled = true
        return label
    }()
    //图片
    lazy var contentImg: MenuUIImageView = {
        let img = MenuUIImageView.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
        img.layer.masksToBounds = true
        img.isUserInteractionEnabled = true
        //缩放
        let tap = UITapGestureRecognizer(target: self, action: #selector(tapGetstureAction(gesture:)))
        img.addGestureRecognizer(tap)
        return img
    }()
    //气泡
    lazy var bubbleImgView: UIImageView = {
        let bubble = UIImageView()
        return bubble
    }()

    lazy var maskImgView: UIImageView = {
        let mask = UIImageView()
        return mask
    }()
    
    @objc func clickSendBtn(sender: UIButton) {
        self.sendStateSegue!(sender)
    }
    
    @objc func clickHeaderBtn() {
        self.headerSegue!(model?.sendUserInfo.userId ?? "")
    }
    
    @objc func tapGetstureAction(gesture: UITapGestureRecognizer) {
        if self.contentImg.menuVC.isMenuVisible {
            self.contentImg.menuVC.setMenuVisible(false, animated: true)
        }
        self.imgTapSegue!(model?.messageImg ?? "", gesture.view?.frame.size ?? CGSize.zero)
    }
    
    var model: MutaChatModel? {
        didSet {
            contentLalel.text = model?.messageContent
            headerBtn.setImage(UIImage.init(named: (model?.sendUserInfo.header ?? "header")!), for: UIControlState.normal)
            self.setMessageOriginWithModel(model!)
            
            if model!.messageImg != "" {
                // cell重用时候清除只有文字的情况下设置的container宽度自适应约束
                self.container.clearAutoWidthSettings()
                self.contentImg.isHidden = false
                let image = UIImage.init(named: (model?.messageImg)!)
                self.contentImg.image = image
                
                // 根据图片的宽高尺寸设置图片约束
                let standardRatio = CGFloat(1.62)
                var ratio = CGFloat()
                var h = image?.size.height
                var w = image?.size.width
                
                if (w! > kMaxChatImageViewWidth || w! > kMaxChatImageViewHeight) {
                    ratio = w!/h!
                    if ratio > standardRatio {
                        w = kMaxChatImageViewWidth
                        h = CGFloat(w! * ((image?.size.height)!/(image?.size.width)!))
                    }else {
                        h = kMaxChatImageViewHeight
                        w = h! * ratio
                    }
                }
                
                self.contentImg.size = CGSize(width: w!, height: h!)
                _ = self.container.sd_layout().widthIs(w!)?.heightIs(h!)
                // 设置container以messageImageView为bottomView高度自适应
                self.container.setupAutoHeight(withBottomView: self.contentImg, bottomMargin: 0)
                // container按照maskImageView裁剪
                self.container.layer.mask = self.maskImgView.layer
                
                self.bubbleImgView.didFinishAutoLayoutBlock = {frame in
                    self.maskImgView.size = frame.size
                }
            }else {
                self.container.layer.mask?.removeFromSuperlayer()
                self.contentImg.isHidden = true
                // 清除展示图片时候_containerBackgroundImageView用到的didFinishAutoLayoutBlock
                self.bubbleImgView.didFinishAutoLayoutBlock = nil
                self.contentLalel.sd_resetLayout().leftSpaceToView(self.container, 20)?.topSpaceToView(self.container, 10)?.autoHeightRatio(0)
                // 设置label横向自适应 rightView高度自适应 bottomView高度自适应
            self.contentLalel.setSingleLineAutoResizeWithMaxWidth(kMaxContainerWidth)
                self.container.setupAutoWidth(withRightView: self.contentLalel, rightMargin: 20)
                self.container.setupAutoHeight(withBottomView: self.contentLalel, bottomMargin: 20)

            }
        }
    }
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.setupView()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setupView() {
        self.selectionStyle = .none
        self.container.addSubview(self.contentLalel)
        self.container.addSubview(self.contentImg)
        self.container.addSubview(self.bubbleImgView)
        container.insertSubview(self.bubbleImgView, at: 0)
        self.contentView.addSubview(self.headerBtn)
        self.contentView.addSubview(self.container)
        self.contentView.addSubview(self.sendStateBtn)

        self.setupAutoHeight(withBottomView: self.container, bottomMargin: 0)
        self.bubbleImgView.sd_layout().spaceToSuperView(UIEdgeInsetsMake(0, 0, 0, 0))
    }
    
    func setMessageOriginWithModel(_ model: MutaChatModel) {
        if model.messageType == .sendToOther {
            self.headerBtn.sd_resetLayout().rightSpaceToView(self.contentView, 10)?.topSpaceToView(self.contentView, 10)?.widthIs(35)?.heightIs(35)
            self.container.sd_resetLayout().topEqualToView(self.headerBtn)?.rightSpaceToView(self.headerBtn, 10)
            self.bubbleImgView.image = UIImage.init(named: "chatto_bg_normal")
            self.sendStateBtn.sd_resetLayout().rightSpaceToView(self.container, 6)?.centerYEqualToView(self.container)?.widthIs(12)?.heightIs(12)

        }else if model.messageType == .sendToMe {
            self.headerBtn.sd_resetLayout().leftSpaceToView(self.contentView, 10)?.topSpaceToView(self.contentView, 10)?.widthIs(35)?.heightIs(35)
            self.container.sd_resetLayout().topEqualToView(self.headerBtn)?.leftSpaceToView(self.headerBtn, 10)
            self.bubbleImgView.image = UIImage.init(named: "chatfrom_bg_normal")
            self.sendStateBtn.sd_resetLayout().leftSpaceToView(self.container, 6)?.centerYEqualToView(self.container)?.widthIs(12)?.heightIs(12)
            
        }
        self.maskImgView.image = bubbleImgView.image
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)

    }
}
